<template>
  <div>
    <div class="top">
      <van-search
        @search="onSearch"
        shape="round"
        v-model="value"
        placeholder="请输入搜索关键词"
      />
    </div>
    <div class="content">
      <div class="types">
        <van-sidebar v-model="activeKey">
          <van-sidebar-item
            @click="changeType"
            v-for="type in types"
            :key="type.id"
            :title="type.name"
          />
        </van-sidebar>
      </div>
      <div class="products">
        <van-list
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <div class="product" v-for="product in pros" :key="product.id">
            <img :src="product.banner" alt="" />
            <p class="proname">{{ product.name }}</p>
            <p class="price">价格：￥{{ product.price }}元</p>
            <van-button @click="addcart(product)" round type="warning"
              >加入购物车</van-button
            >
          </div>
        </van-list>
      </div>
    </div>
    <van-popup
      v-model="show"
      position="bottom"
      closeable
      close-icon-position="float left"
      :style="{ height: '90%' }"
    >
      <div class="products">
        <van-list
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <div class="product" v-for="product in pross" :key="product.id">
            <img :src="product.banner" alt="" />
            <p class="proname">{{ product.name }}</p>
            <p class="price">价格：￥{{ product.price }}元</p>
            <van-button @click="addcart(product)" round type="warning"
              >加入购物车</van-button
            >
          </div>
        </van-list>
      </div>
    </van-popup>
  </div>
</template>

<script>
import Vue from "vue";
import { Search } from "vant";
import { Sidebar, SidebarItem } from "vant";
import { getTypes, getPro, addCart } from "@/request";
import { List } from "vant";
import { Button } from "vant";
import { getCookie } from "@/utils/cookie";
import { Toast } from "vant";
import { Popup } from "vant";

Vue.use(Popup);
Vue.use(Toast);
Vue.use(Button);
Vue.use(List);
Vue.use(Sidebar);
Vue.use(SidebarItem);
Vue.use(Search);
export default {
  data() {
    return {
      value: "",
      activeKey: 0,
      types: [],
      pros: [],
      pross: [],
      loading: false,
      finished: false,
      // 定义当前第几页
      page: 1,
      typename: "",
      show: false,
    };
  },
  created() {
    this.typename = this.$route.query.typename || "全部";
    this.request();
  },
  methods: {
    async request() {
      var types = await getTypes();
      // 给所有分类的最前面添加一个全部
      types.unshift({
        id: +new Date(),
        name: "全部",
      });
      this.types = types;
      this.activeKey = this.types.findIndex(
        (item) => item.name === this.typename
      );
    },
    onLoad() {
      this.getProducts();
    },
    getProducts() {
      getPro(this.typename).then((data) => {
        var pros = data.slice((this.page - 1) * 5, this.page * 5);
        if (pros.length < 5) {
          this.finished = true;
        } else {
          this.page++;
        }
        this.loading = false;
        this.pros = this.pros.concat(pros);
      });
    },
    // 点击分类的事件
    changeType(index) {
      // console.log(index); // 是当前正在点击的分类在types中的下标
      this.typename = this.types[index].name;
      this.page = 1;
      this.pros = [];
      this.finished = false;
      this.getProducts();
    },
    // 加入购物车的函数
    addcart(product) {
      var _this = this;
      // 判断用户是否登录
      var username = getCookie("username");
      // 没有登录就强行跳转到登录
      if (!username) {
        Toast.fail({
          message: "请先登录！",
          onClose() {
            // 先将当前路径存储在本地存储 - 做标记
            window.localStorage.setItem("url", "/types");
            _this.$router.push("/my/login");
          },
        });
        return;
      }
      // 如果登录了就准备数据
      // 整理数据： 当前商品的数据+用户信息+商品的数量
      product.username = username;
      product.number = 1;
      // console.log(product);
      // 发送请求
      // 为了让多个用户可以添加同一个商品到购物车，需要在添加数据的时候，让系统自动生成id，我们不要手动传递id
      // console.log(product);
      // 将product中的id删除
      if (product.id) {
        product.pid = product.id;
        delete product.id;
      }
      addCart(product).then((data) => {
        // console.log(data);
        Toast.success(data.msg);
      });
    },
    onSearch(val) {
      this.showPopup();
      this.typename = 0;
      this.page = 1;
      this.pross = [];
      getPro("全部").then((data) => {
        var j = 0;
        var pross = [];
        for (var i = 0; i < data.length; i++) {
          var a = data[i].name;

          if (a.match(val)) {
            pross[j] = data[i];
            j = j + 1;
          }
        }

        this.pross = pross;
        // this.pros = this.pros.concat(pros)
      });
      // console.log(this.pros);
    //   this.loading = true,
      this.finished = true;
    },
    showPopup() {
      this.show = true;
    },
  },
};
</script>

<style scoped>
.top {
  width: 100%;
  position: fixed;
  left: 0;
  top: 0;
}
.types {
  float: left;
  margin-bottom: 50px;
  width: 25%;
  position: fixed;
  left: 0;
  top: 50px;
}
.products {
  float: right;
  margin: 0 30px 50px 80px;
  width: 65%;
}
.product {
  width: 100%;
  border: 1px solid #ccc;
  border-radius: 10px;
  padding: 10px;
}
.product img {
  width: 100%;
  border-radius: 10px;
}
.product .price {
  font-size: 20px;
  font-weight: bold;
  color: #f00;
}
.product .van-button {
  width: 100%;
  font-size: 18px;
}
.product .proname {
  line-height: 28px;
}
</style>
